package com.roundarch.www.ui;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.roundarch.www.model.Authorities;
import com.roundarch.www.model.Comment;
import com.roundarch.www.model.Files;
import com.roundarch.www.model.Post;
import com.roundarch.www.model.User;
import com.roundarch.www.util.StringUtils;
import com.roundarch.www.util.propertyeditor.EntityPropertyEditor;


@Controller
@RequestMapping("/post")
public class PostController extends AbstractEntityController<Post> {

	private final Log logger = LogFactory.getLog(getEntityClass());

	
	
	public void buildShowModel(Post entity, Model model,HttpServletRequest request) {
		// TODO Auto-generated method stub
		super.buildShowModel(entity, model,request);
		model.addAttribute("comment", BeanUtils.instantiateClass(Comment.class));
		model.addAttribute("file", BeanUtils.instantiateClass(Files.class));
		Principal principal = null;
		String loginName = null;
		if(request.getUserPrincipal() != null) {
            loginName = request.getUserPrincipal().getName();
            principal = request.getUserPrincipal();
        }
		model.addAttribute("user",
				getEntityService().find(User.class, "userName", loginName));
	}
	
	@ModelAttribute("entity")
    public Post entity(HttpServletRequest request)
    {
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id))
            return getEntityService().find(Long.parseLong(id),getEntityClass());

        Post t = BeanUtils.instantiateClass(getEntityClass());
        return t;
    }
    
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(
			@Valid @ModelAttribute("entity") Post entity,
			BindingResult result,
			Model model,
			@RequestParam(value = "saveTarget", defaultValue = "show") String saveTarget,
			HttpServletRequest request) {

		if (result.hasErrors()) {
			// TODO set 'flash' to error
			buildEditModel(entity, model,request);
			return StringUtils.joinPath(getRootRequestMapping(), "edit");
		}

		try {
			String loginName = null;
			if(request.getUserPrincipal() != null) {
	            loginName = request.getUserPrincipal().getName();
	        }
			
			getEntityService().save(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:" + buildSaveTargetUrl(saveTarget, entity);
	}
	
	

	@Override
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		super.initBinder(binder);

		binder.registerCustomEditor(User.class,
				new EntityPropertyEditor<User>(getEntityService(),
						User.class));
	}
	
	public void buildEditModel(Post entity, Model model,HttpServletRequest request) {
		super.buildEditModel(entity, model,request);
		
		Principal principal = null;
		String loginName = null;
		if(request.getUserPrincipal() != null) {
            loginName = request.getUserPrincipal().getName();
            principal = request.getUserPrincipal();
        }
		model.addAttribute("user",
				getEntityService().find(User.class, "userName", loginName));
		logger.info("Logged in user is "+loginName);
		
	}
	
	
	
	
	
	
}
